
import { logoutAction } from '../utils/index';
import axios from 'axios';
import { toast } from 'react-toastify';

const {VITE_APP_API_URL} = import.meta.env
// console.log(VITE_APP_URL)

// react-toastify
// https://fkhadra.github.io/react-toastify/installation

const robotsapi = axios.create({
    baseURL: localStorage.getItem("apiurl")  || VITE_APP_API_URL,
    timeout: 15000,
    withCredentials: true,
})


robotsapi.interceptors.request.use(config => {
    return config;
}, err => {
    // alert(`request timeout`)
    toast.error('request timeout')
    return Promise.resolve(err);
});


robotsapi.interceptors.response.use(data => {
    // console.log('interceptors.response data=', data)
    const { code, message } = data.data

    if (code != 0) {
        if(code === 422 || code === 401) {
            logoutAction()
        } else {
            let msg = message || "request error"
            // alert(`${msg}`)
            toast.error(message)
            return Promise.reject(new Error(msg))
        }
    }

    return data.data;
}, err => {
    // console.log('interceptors.response err=', err);
    const {message, response} = err

    if(!response) {
        // alert(`${message}`)
        toast.error(message)
        return Promise.reject(err);
    }

    if (response.status !== 200) {
        let data = err.response.data
        let msg = (data && data?.message) || "server error"

        // alert(`${msg}`)
        toast.error(msg)
    }

    return Promise.reject(err);
})




export {
    robotsapi, 
}
